package znet

import (
	"fmt"
	"net"

	"zinx-my/ziface"
)

type Server struct {
	Name      string
	IPVersion string
	IP        string
	Port      int
}

// CallBackToClient 写死一个回调函数
func CallBackToClient(conn *net.TCPConn, data []byte, cnt int) error {
	fmt.Println("[Conn Handle] CallBackToClient...")

	if _, err := conn.Write(data[:cnt]); err != nil {
		fmt.Println("write back buf error:", err)
		return err
	}

	return nil
}

func (s *Server) Start() {
	fmt.Printf("[Start] Server Listener at IP: %s, Port: %d, is starting\n", s.IP, s.Port)

	addr, err := net.ResolveTCPAddr(s.IPVersion, fmt.Sprintf("%s:%d", s.IP, s.Port))
	if err != nil {
		fmt.Println("resolve tcp addr error:", err)
		return
	}

	listener, err := net.ListenTCP(s.IPVersion, addr)
	if err != nil {
		fmt.Println("listen tcp error:", err)
		return
	}

	fmt.Println("start Zinx server success", s.Name, "listening")

	var cid uint32 = 0

	for {
		conn, err := listener.AcceptTCP()
		if err != nil {
			fmt.Println("accept tcp error:", err)
			continue
		}

		dealConn := NewConnection(conn, cid, CallBackToClient)
		cid++

		// 启动
		dealConn.Start()

		// go func() {
		// 	for {
		// 		buf := make([]byte, 512)
		// 		cnt, err := conn.Read(buf)
		// 		if err != nil {
		// 			fmt.Println("read conn buf error:", err)
		// 			continue
		// 		}
		//
		// 		if _, err := conn.Write(buf[:cnt]); err != nil {
		// 			fmt.Println("write back buf error:", err)
		// 		}
		// 	}
		// }()
	}
}

func (s *Server) Stop() {

}

func (s *Server) Serve() {
	go s.Start()

	// 直接阻塞
	select {}
}

func NewServer(name string) ziface.IServer {
	return &Server{
		Name:      name,
		IPVersion: "tcp4",
		IP:        "0.0.0.0",
		Port:      8999,
	}
}
